﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;

namespace Solution.Mvc.Areas.More.Controllers
{
    public class CkUploadImageController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }
        public JsonResult BindDirectoryList(string myName)
        {
            try
            {
                ImageFolder = myName;
                string[] directories = Directory.GetDirectories(FileImageFolder);
                directories = Array.ConvertAll<string, string>(directories, delegate(string directory) { return directory.Substring(directory.LastIndexOf('\\') + 1); });
                return Json(directories, JsonRequestBehavior.AllowGet);

            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult CreateNewFolder(string myName)
        {
            try
            {
                string name = UniqueDirectory(myName);
                Directory.CreateDirectory(FileImageFolderRoot + "/" + name);
                return Json("ok", JsonRequestBehavior.AllowGet);
            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult GetImageWidthHeight(string myName)
        {
            try
            {
                int width = 0, height = 0;
                Image img = Image.FromFile(FileImageFolder + "/" + myName);
                GetImageSize(img, ref width, ref height);
                var res = new
                {
                    imgWidth = width,
                    imgHeight = height
                };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult GetImageHeightByWidth(string myName, int myWidth)
        {
            try
            {
                int width = 0, height = 0;
                Image img = Image.FromFile(FileImageFolder + "/" + myName);
                GetImageSize(img, ref width, ref height);
                int myHeight = height;
                float Mod = (float)myWidth / (float)width;
                myHeight = (int)(height * Mod);
                return Json(myHeight, JsonRequestBehavior.AllowGet);
            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult DeleteFolder(string myName)
        {
            try
            {
                if (myName.Length > 1)
                    Directory.Delete(FileImageFolderRoot + "/" + myName, true);
                return Json("ok", JsonRequestBehavior.AllowGet);

            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult DeleteItem(string myName)
        {
            try
            {
                System.IO.File.Delete(FileImageFolder + "/" + myName);
                return Json("ok", JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult RenameItem(string myName, string newName)
        {
            try
            {
                if (IsImage(newName))
                {
                    string filename = UniqueImgName(newName);
                    System.IO.File.Move(FileImageFolder + "/" + myName, FileImageFolder + "/" + filename);
                    return Json("ok", JsonRequestBehavior.AllowGet);
                }
                else
                    return Json("noimg", JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult ResizeThisImage(string myName, int myWidth, int myHeight)
        {
            try
            {
                Image img = Image.FromFile(FileImageFolder + "/" + myName);
                Image myImg = resizeImage(img, myWidth, myHeight);
                System.IO.File.Delete(FileImageFolder + "/" + myName);
                myImg.Save(FileImageFolder + "/1_" + myName);
                myImg.Dispose();
                System.IO.File.Move(FileImageFolder + "/1_" + myName, FileImageFolder + "/" + myName);
                return Json("ok", JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult BindImageList(string myName)
        {
            try
            {
                if (myName == null)
                    myName = "";
                if (myName.Length > 0 && myName != "Root")
                    Session["folder"] = "/" + myName;
                else
                    Session["folder"] = "";

                string[] files = Directory.GetFiles(FileImageFolder, "*");
                files = Array.FindAll(files, delegate(string f) { return IsImage(f); });

                for (int i = 0; i < files.Length; i++)
                {
                    if (IsImage(files[i]))
                        files[i] = Url.Content(ImageFolder) + "/" + files[i].Substring(files[i].LastIndexOf('\\') + 1);
                }

                return Json(files, JsonRequestBehavior.AllowGet);

            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }
        [HttpPost]
        public JsonResult UploadImage(FormCollection context)
        {
            try
            {
                var r = new System.Collections.Generic.List<ViewDataUploadFilesResult>();
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    string FileName = string.Empty;
                    if (HttpContext.Request.Browser.Browser.ToUpper() == "IE")
                    {
                        string[] files = hpf.FileName.Split(new char[] { '\\' });
                        FileName = files[files.Length - 1];
                    }
                    else
                    {
                        FileName = hpf.FileName;
                    }
                    if (hpf.ContentLength == 0)
                        continue;
                    string _filename = UniqueImgName(FileName);
                    string savedFileName = FileImageFolder + "/" + _filename;
                    hpf.SaveAs(savedFileName);

                    r.Add(new ViewDataUploadFilesResult()
                    {
                        //Thumbnail_url = savedFileName,
                        Name = FileName,
                        Length = hpf.ContentLength,
                        Type = hpf.ContentType
                    });
                    var uploadedFiles = new
                    {
                        files = r.ToArray()
                    };
                    return Json(uploadedFiles, JsonRequestBehavior.AllowGet);
                }
                return Json("ok", JsonRequestBehavior.AllowGet);

            }
            catch
            {

                return Json("no", JsonRequestBehavior.AllowGet);
            }
        }

        protected string UniqueDirectory(string directoryname)
        {
            string newdirectoryname = directoryname.Replace(' ', '_');

            for (int i = 1; Directory.Exists(FileImageFolderRoot + "/" + newdirectoryname); i++)
            {
                newdirectoryname = directoryname + "(" + i + ")";
            }
            return newdirectoryname;
        }
        protected string UniqueImgName(string imgName)
        {
            string newImgName = imgName.Replace(' ', '_');
            if (System.IO.File.Exists(FileImageFolder + "/" + imgName))
                newImgName = DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + imgName;
            return newImgName;
        }

        //properties
        protected string ImageFolderRoot
        {
            // get { return ConfigurationManager.AppSettings["ImageRoot"]; }
            get { return "~/Content/Images/Upload"; }
        }

        protected string FileImageFolderRoot
        {
            get { return Server.MapPath(ImageFolderRoot); }
        }

        protected string ImageFolder
        {
            get { return ImageFolderRoot + Session["folder"]; }
            set { Session["folder"] = value; }
        }

        protected string FileImageFolder
        {
            get { return Server.MapPath(ImageFolder); }
        }



        //util methods
        private bool IsImage(string file)
        {
            return file.EndsWith(".jpg", StringComparison.CurrentCultureIgnoreCase) ||
                file.EndsWith(".jpeg", StringComparison.CurrentCultureIgnoreCase) ||
                file.EndsWith(".jpe", StringComparison.CurrentCultureIgnoreCase) ||
                file.EndsWith(".bmp", StringComparison.CurrentCultureIgnoreCase) ||
                file.EndsWith(".tif", StringComparison.CurrentCultureIgnoreCase) ||
                file.EndsWith(".gif", StringComparison.CurrentCultureIgnoreCase) ||
                file.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase);
        }
        public void GetImageSize(Image img, ref int width, ref int height)
        {
            width = img.Width;
            height = img.Height;
            img.Dispose();
        }
        public Image resizeImage(Image img, int width, int height)
        {
            Bitmap b = new Bitmap(width, height);
            Graphics g = Graphics.FromImage((Image)b);

            //option chat luong hinh
            //Các thuật toán (được xây dựng trong .NET): 
            //Bicubic
            //Bilinear
            //Default
            //High
            //HighQualityBicubic
            //HighQualityBilinear
            //Invalid
            //Low
            //NearestNeighbor
            g.InterpolationMode = InterpolationMode.Bicubic;    // Specify here			

            g.DrawImage(img, 0, 0, width, height);
            g.Dispose();
            img.Dispose();
            return (Image)b;
        }
        public Image Resize(Image img, float percentage)
        {
            //lấy kích thước ban đầu của bức ảnh
            int originalW = img.Width;
            int originalH = img.Height;
            //tính kích thước cho ảnh mới theo tỷ lệ đưa vào
            int resizedW = (int)(originalW * percentage);
            int resizedH = (int)(originalH * percentage);

            //tạo 1 ảnh Bitmap mới theo kích thước trên
            Bitmap bmp = new Bitmap(resizedW, resizedH);
            //tạo 1 graphic mới từ Bitmap
            Graphics graphic = Graphics.FromImage((Image)bmp);
            //vẽ lại ảnh ban đầu lên bmp theo kích thước mới
            graphic.DrawImage(img, 0, 0, resizedW, resizedH);
            //giải phóng tài nguyên mà graphic đang giữ
            graphic.Dispose();
            //return the image
            return (Image)bmp;
        }
        //Ví dụ: Muốn giảm 1 nửa kích thước của ảnh "abc.jpg" ta làm như sau:
        //   var ifirst = Image.FromFile("abc.jpg");
        //   var iresize = Resize(ifirst, 0.5F);
        //   iresize.Save("a.jpg");



    }
    public class ViewDataUploadFilesResult
    {
        public string Thumbnail_url { get; set; }
        public string Name { get; set; }
        public int Length { get; set; }
        public string Type { get; set; }
    }

}
